<template>
    <view class="map-wrapper">
		<BMap ref="mapRef" />
		<view class="city" @click="handleCity()">{{city.name}}</view>
		<view class="system" @click="handleSystem()">设置</view>
      	<view class="ai-btn" @click="goChat">小鹏ai</view>
    	
		<SelectPoint v-if="loadingFinish" @confirm="handleConfrimPoint"/>
    </view>
</template>
<script setup>
    import {computed, onMounted, provide, ref, watch} from 'vue';
	import { useStore } from 'vuex';
	import BMap from '../../component/BMap.vue';
	import SelectPoint from './modules/SelectPoint.vue';
	//sse连接
	import { useSseService } from '@/service/sseService-web.js';
	//sse接收到信息
	import { useMessageStore } from '@/store/message-web.js';
	import { locationService } from '@/utils/location.js'
	//jwt解码
	import { decodeToken } from '@/utils/decodeToken.js';
	
	const messageStore = useMessageStore();
	// messageStore.latestMessage获取最新消息
	const { eventData, error, isConnected, connectSSE, reconnectSSE, closeSSE } = useSseService();
	//实时定位
	const realTimeLocation = ref({
	  longitude: null,
	  latitude: null,
	  // address: null
	});
	const isRealTimeLocating = ref(false);
	
	const $store = useStore();
	const mapRef = ref(null);
	let city = computed(()=> $store.state.city);
	let loadingFinish = ref(false);
	provide('mapSearch',(str,cb) => mapRef.value.search(cb, str));
	
	const token = computed(()=> $store.state.token);
	onMounted(()=>{
		// toRealTimeLocation();
		
		//获取token
		// console.log("地图页面获取用户token：",token.value)
		if(token.value){
			//解码token
			const decodedToken = decodeToken(token.value);
			console.log("解码token：",decodedToken);
			    
			if (!decodedToken) {
			    console.error('无法从token中获取用户ID');
				return;
			}else{
				// console.log("token中解码获取用户ID：",decodedToken?.phone,";身份：",decodedToken?.identity);
				connectSSE(decodedToken.phone, decodedToken.identity);
				
			}
		}
		
		setCenter();
		watch(city, setCenter);
		// 临时加的一个延迟
		setTimeout(()=>{
			loadingFinish.value = true
		},7000)
	})
	
	/**
	 * 开启实时定位
	 */
	const toRealTimeLocation = async () => {
	  if (isRealTimeLocating.value) {
	    locationService.stopRealTimeLocation();
	    isRealTimeLocating.value = false;
	  } else {
	    try {
	      // 注册位置变化回调
	      locationService.onLocationChange((location) => {
	        realTimeLocation.value = location;
	      });
	      
	      await locationService.startRealTimeLocation();
	      isRealTimeLocating.value = true;
	      uni.showToast({
	        title: '已开启实时定位',
	        icon: 'success'
	      });
	    } catch (error) {
	      uni.showToast({
	        title: '开启实时定位失败',
	        icon: 'none'
	      });
	      console.error('开启实时定位失败:', error);
	    }
	  }
	};
 /**
  * @Description: 城市变更
  * 重新设置地图显示区域
  * 清除已画好的路线
  * @return {*}
  */
 	function setCenter (){
		const center = city.value.center.split(',');
		mapRef.value.setCenter(...center);
		setTimeout(()=>mapRef.value.clearDriving(), 500);
	}	
 /**
  * @Description:  确认路线
  * 绘制路线，页面状态改为价格
  * @param {*} start
  * @param {*} end
  * @return {*}
  */	
	const handleConfrimPoint = async (start, end) =>{
		const [startLng, startLat] = start.location;
		const [endLng, endLat ] = end.location;
		uni.navigateTo({
			url : `/pages/createOrder?slng=${startLng}&slat=${startLat}&elng=${endLng}&elat=${endLat}&s=${start.name}&e=${end.name}`
		})
	}
 /**
  * @Description: 重新选城市
  * @return {*}
  */	
	const handleCity = () =>{
  		uni.navigateTo({url: '/pages/city'});
	}

	const handleSystem = () =>{
		uni.navigateTo({url: '/pages/account'});
	}
	const goChat = () => {
  uni.navigateTo({
    url: '/pages/chat/chat'
  })
}
</script>
<style scoped lang="scss">

	.map-wrapper {
		width: 100%;
		height: 100vh;
	}
	.city,.system{
		position: fixed;
		background: #fff;
		padding: 7rpx 15rpx 10rpx;
		z-index: 9;
		top: calc(var(--window-top) + 30rpx);
		right: 30rpx;
		border-radius: 8rpx;
		box-shadow: 0 3rpx 5rpx 5rpx #ccc;
		font-size: $uni-font-size-sm;
		color: $uni-text-color;
		display: flex;
		align-items: center;
	}
	.city{
		left: 30rpx;
		right: auto;
		&::after{
			content: '';
			display: block;
			border: 10rpx solid #666;
			border-right-color: transparent;
			border-left-color: transparent;
			border-bottom-color: transparent;
			margin-left: 10rpx;
			margin-top: 12rpx;
			border-radius: 4rpx;
		}

	}
	.ai-btn {
  position: fixed;
  right: 40rpx;
  bottom: 1000rpx;
  z-index: 9999;
  background: linear-gradient(90deg, #4f8cff 0%, #34e7e4 100%);
  color: #fff;
  border: none;
  outline: none;
  border-radius: 30rpx;
  padding: 10rpx 28rpx;
  font-size: 28rpx;
  font-weight: bold;
  box-shadow: 0 2rpx 8rpx 0 rgba(79,140,255,0.15);
  transition: box-shadow 0.2s;
  white-space: nowrap;
  display: inline-block;
  min-width: 100rpx;
  max-width: 220rpx;
  text-align: center;
  cursor: pointer;
}
.ai-btn:active {
  box-shadow: 0 2rpx 6rpx 0 rgba(79,140,255,0.12);
  opacity: 0.92;
}
</style>